/**
 * 需求简历，渠道发布--对外岗位表单
 */
import React from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { BlockTitle } from '@/molecules';
import { BottomAction } from '@/components';
import { useRequest } from '@/hooks';
import { Form, Card, Button, Input, InputNumber, Select, Radio, message } from 'antd';
import { dictionaryList } from '@/services/dictionary';
import { history } from 'umi'
import { DemandFieldUpdate } from '@/pages/Recruitment/Channel/containers';
import { debounce } from 'lodash';
import { getChannelPost, getOrgCity, getPositionTags, updateChannelPost } from '../service';

const { TextArea } = Input;
const { Option } = Select;

const formLayout = {
    wrapperCol: { span: 21 },
    labelCol: { span: 3 }
};

const getCity = arr => {
    if (arr && arr.length > 0) {
        const temp = [];
        arr.forEach(item => {
            const area = item?.area || '';
            const tempArr = area.split(',');
            let str = '';
            if (tempArr.length > 3) {
                str = tempArr[2] === '市辖区' ? tempArr[1] : tempArr[2];
            } else if (tempArr.length > 0) {
                str = tempArr[tempArr.length - 1];
            }
            if (!temp.includes(str)) {
                temp.push(str);
            }
        });
        return temp;
    }
    return [];
};

const monthMoney = ['12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'];

const PostForm = ({ form, location }) => {
    const { getFieldDecorator } = form;
    const [submitting, setSubmitting] = React.useState(false);
    const [dictObj, setDictObj] = React.useState(null);
    const { query } = location;

    // 表单设置
    const { data: formData = {}, loading: postFetching, run: formRun } = useRequest(() =>
        getChannelPost(query.recruitCode)
    );
    const { data: postData } = formData;

    // 获取职位关键词列表
    const { data: tagList, run: fetchPositionTags } = useRequest(tagName => getPositionTags(tagName), {
        // debounceInterval: 400,
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return [...new Set(data || [])];
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    React.useEffect(() => {
        if (!postData) {
            return;
        }
        const {
            dutyName,
            workNature,
            workYears,
            recruitDegree,
            workCity,
            recruitNums,
            recruitSex,
            positionDuty,
            minSalary,
            maxSalary,
            salaryNum,
            jobRequirement,
            positionTag
        } = postData;

        const finalPositionDuty = positionDuty?.replace('</br>', '\n');

        form.setFieldsValue({
            dutyName,
            recruitNums,
            recruitDegree,
            workNature,
            workYears,
            recruitSex,
            positionDuty: finalPositionDuty,
            workCity,
            minSalary,
            maxSalary,
            jobRequirement,
            salaryNum: salaryNum || undefined,
            positionTag: positionTag ? positionTag.split(',') : undefined
        });
    }, [postData]);

    // 工作城市
    const { data: cityList, run: fetchCityList } = useRequest(getOrgCity, {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return getCity(data);
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    // 需获取当前数据所在部门
    React.useEffect(() => {
        if (postData) {
            fetchCityList(postData.companyCode);
        }
    }, [postData]);

    const fetchDictionary = async () => {
        const res = await dictionaryList({
            codes: ['jobNature', 'candidateSexType', 'agreeType', 'timeEmployedType']
        });
        const { code, data, msg } = res;
        if (code === 10000) {
            const obj = {};
            data.forEach(item => {
                if (obj[item.code]) {
                    obj[item.code].push(item);
                } else {
                    obj[item.code] = [item];
                }
            });
            setDictObj(obj);
        } else {
            message.error(msg);
        }
    };

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const { workCity, positionTag } = values;
                if (positionTag && positionTag.length > 0) {
                    if (positionTag.some(tag => tag.length > 20)) {
                        message.error('单个职位关键词长度不可超过20个字符');
                        return;
                    }
                }
                const finalWorkCity = Array.isArray(workCity) ? workCity.join(',') : workCity;
                const res = await updateChannelPost(postData?.outwardId, {
                    ...values,
                    workCity: finalWorkCity,
                    positionTag: positionTag && positionTag.length > 0 ? positionTag.join(',') : ''
                });
                if (res.code === 10000) {
                    setSubmitting(true);
                    message.success('更新成功！');
                    history.goBack();
                } else {
                    message.error(res.msg);
                }
                setSubmitting(false);
            }
        });
    };

    React.useEffect(() => {
        fetchDictionary();
    }, []);

    const renderOptions = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Option>
            ));
        }
        return null;
    };

    const renderOptionsMonth = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item} key={item}>
                    {item}
                </Option>
            ));
        }
        return null;
    };

    const renderRadios = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Radio value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Radio>
            ));
        }
        return null;
    };

    const validatorMin = (rule, value, callback) => {
        const { getFieldValue } = form;
        if (Number(value) > Number(getFieldValue('maxSalary'))) {
            callback('薪资最小值不能大于最大值');
        }
        callback();
        form.validateFields(['maxSalary']);
    };

    const validatorMax = (rule, value, callback) => {
        const { getFieldValue } = form;
        if (Number(value) < Number(getFieldValue('minSalary'))) {
            callback('');
        }
        callback();
        form.validateFields(['minSalary']);
    };

    const handleTagChange = () => {
        fetchPositionTags('');
    };

    const handleTagSearch = debounce(value => {
        fetchPositionTags(value?.trim() || '');
    }, 400);

    return (
        <PageHeaderWrapper>
            <DemandFieldUpdate style={{ marginBottom: 0 }} onRefresh={formRun} outwardId={postData?.outwardId} />
            <Card
                title="编辑岗位对外信息"
                bordered={false}
                loading={postFetching}
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button type="primary" onClick={handleSubmit} loading={submitting}>
                            保存
                        </Button>
                    </BottomAction>
                }
            >
                <BlockTitle title="基本信息" style={{ marginBottom: 24 }} />
                <Form {...formLayout}>
                    <Form.Item label="岗位名称">
                        {getFieldDecorator('dutyName', {
                            rules: [
                                {
                                    required: true,
                                    message: '岗位名称不能为空',
                                    whitespace: true
                                }
                            ]
                        })(<Input style={{ width: '40%' }} placeholder="请输入岗位名称" disabled />)}
                    </Form.Item>
                    <Form.Item label="招聘人数">
                        {getFieldDecorator('recruitNums', {
                            rules: [
                                {
                                    required: true,
                                    message: '招聘人数不能为空'
                                }
                            ]
                        })(
                            <InputNumber
                                min={0}
                                max={999}
                                precision={0}
                                placeholder="请输入招聘人数"
                                style={{ width: '40%' }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="工作城市">
                        {getFieldDecorator('workCity', {
                            rules: [
                                {
                                    required: true,
                                    message: '工作城市不能为空'
                                }
                            ]
                        })(
                            <Select style={{ width: '40%' }} mode="multiple" placeholder="请选择工作城市" allowClear>
                                {cityList?.map(item => (
                                    <Option value={item} key={item}>
                                        {item}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="工作性质">
                        {getFieldDecorator('workNature')(<Radio.Group>{renderRadios(dictObj?.jobNature)}</Radio.Group>)}
                    </Form.Item>
                </Form>
                <BlockTitle title="岗位要求" style={{ marginBottom: 24 }} />
                <Form {...formLayout}>
                    <Form.Item label="经验和学历" style={{ marginBottom: 0 }} required>
                        <div style={{ display: 'flex' }}>
                            <Form.Item label="" colon={false} style={{ width: '19.6%', marginRight: 8 }}>
                                {getFieldDecorator('workYears', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '工作年限不能为空'
                                        }
                                    ]
                                })(
                                    <Select placeholder="请选择工作年限" allowClear>
                                        {renderOptions(dictObj?.timeEmployedType)}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="" colon={false} style={{ width: '19.6%' }}>
                                {getFieldDecorator('recruitDegree', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '学历不能为空'
                                        }
                                    ]
                                })(
                                    <Select placeholder="请选择学历" allowClear>
                                        {renderOptions(dictObj?.agreeType)}
                                    </Select>
                                )}
                            </Form.Item>
                        </div>
                    </Form.Item>
                    <Form.Item label="性别">
                        {getFieldDecorator('recruitSex')(
                            <Radio.Group>{renderRadios(dictObj?.candidateSexType)}</Radio.Group>
                        )}
                    </Form.Item>
                    <Form.Item required label="薪资范围" style={{ marginBottom: 0 }}>
                        <div style={{ display: 'flex' }}>
                            <Form.Item label="" colon={false} style={{ width: '9%' }}>
                                {getFieldDecorator('minSalary', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '不能为空'
                                        },
                                        {
                                            validator: validatorMin
                                        }
                                    ]
                                })(
                                    <InputNumber placeholder="请输入" min={0} precision={0} style={{ width: '100%' }} />
                                )}
                            </Form.Item>
                            <span style={{ padding: '0 8px' }}>K</span>
                            <span style={{ margin: '0 8px' }}>~</span>
                            <Form.Item label="" colon={false} style={{ width: '9%' }}>
                                {getFieldDecorator('maxSalary', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '不能为空'
                                        },
                                        {
                                            validator: validatorMax
                                        }
                                    ]
                                })(
                                    <InputNumber placeholder="请输入" min={0} precision={0} style={{ width: '100%' }} />
                                )}
                            </Form.Item>
                            <span style={{ padding: '0 8px' }}>K</span>
                            <span style={{ padding: '0 8px' }}>*</span>
                            <Form.Item label="" colon={false} style={{ width: '10%' }}>
                                {getFieldDecorator('salaryNum', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '不能为空'
                                        }
                                    ]
                                })(
                                    <Select placeholder="请选择" allowClear style={{ width: '100%' }}>
                                        {renderOptionsMonth(monthMoney)}
                                    </Select>
                                )}
                            </Form.Item>
                            <span style={{ padding: '0 8px' }}>{postData?.companyCurrencyCode || '薪'}</span>
                        </div>
                    </Form.Item>
                    <Form.Item label="匹配职位">
                        <div>
                            {postData?.positionName || '--'}/{postData?.rankValue || '--'}
                        </div>
                    </Form.Item>
                    <Form.Item label="职位要求">
                        {getFieldDecorator('positionDuty', {
                            rules: [
                                {
                                    required: true,
                                    message: '职位要求不能为空'
                                }
                            ]
                        })(
                            <TextArea
                                placeholder="请输入职位要求"
                                autoSize={{ minRows: 6, maxRows: 9 }}
                                maxLength={2500}
                                style={{ width: '40%' }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="岗位职责">
                        {getFieldDecorator('jobRequirement', {
                            rules: [
                                {
                                    required: true,
                                    message: '岗位职责不能为空'
                                }
                            ]
                        })(
                            <TextArea
                                placeholder="请输入岗位职责"
                                autoSize={{ minRows: 6, maxRows: 9 }}
                                maxLength={2500}
                                style={{ width: '40%' }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="职位关键词">
                        {getFieldDecorator('positionTag')(
                            <Select
                                mode="tags"
                                style={{ width: '40%' }}
                                placeholder="请选择职位关键词"
                                allowClear
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                onFocus={handleTagChange}
                                onSearch={handleTagSearch}
                                tokenSeparators={[',']}
                                filterOption={false}
                            >
                                {tagList?.map(item => (
                                    <Option value={item} key={item}>
                                        {item}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(PostForm);
